package com.buric.gateway.config;

import com.alibaba.nacos.shaded.com.google.common.collect.Lists;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.AntPathMatcher;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * 白名单配置
 * @author zhou.wei
 * @description 白名单撇嘴
 * @date 2023/8/22 11:24
 */
@Configuration
@RefreshScope
@ConfigurationProperties(prefix = "security.ignore")
public class IgnoreWhiteProperties {
    /**
     * 放行白名单配置，网关不校验此处的白名单
     */
    private List<String> whites = new ArrayList<>();

    public List<String> getWhites() {
        return whites;
    }

    public void setWhites(List<String> whites) {
        this.whites = whites;
    }


    /**
     * 是否存在白名单中，支持正则匹配
     * @param url
     * @return
     */
    public boolean isWhite(String url) {

        List<String> swaggerUrlList = Lists.newArrayList("/**/swagger-ui/index.html",
                "/**/swagger-resources/**","/swagger-resources/**", "/**/v2/api-docs",
                "/**/v3/api-docs", "/**/webjars/**",
                "/**/actuator/**","/**/doc.html","/api-auth/authAdmin/captcha");

        // 创建一个 RequestMatcher 列表
        // 使用 AntPathMatcher 匹配路径
        boolean b = swaggerUrlList.stream()
                .anyMatch(pattern -> new AntPathMatcher().match(pattern, url));
        if(b){
            return true;
        }
        for (String link : whites) {
            if (url.matches(link)) {
                return true;
            }
        }
        return false;
    }
}
